package cn.wxxyhw.Dao;

import cn.wxxyhw.Entity.Comment;
import cn.wxxyhw.Util.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * 评论操作
 * @Author: 洪稳
 * @Date: 2019/6/3
 */
@Repository
public class CommentDao {

    static QueryRunner queryRunner ;
    static {
        queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    }
    /**
     * 评论保存
     * @param comment
     */
    public void save(Comment comment) {
        String sql = "insert into comment(liuyanId,articleId,fromName,toName,date,fromImage,content,fromId,toId) values(?,?,?,?,?,?,?,?,?)";
        try {
            queryRunner.update(sql,comment.getLiuyanId(),
                    comment.getArticleId(),
                    comment.getFromName(),
                    comment.getToName(),
                    comment.getDate(),
                    comment.getFromImage(),
                    comment.getContent(),
                    comment.getFromId(),
                    comment.getToId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到全部评论
     * @return
     */
    public List<Comment> getAll() {
        List<Comment> list = null;
        String sql = "select * from comment";
        try {
             list = queryRunner.query(sql, new BeanListHandler<>(Comment.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 删除评论
     * @param id 评论id
     */
    public void del(int id) {
        String sql = "delete from comment where id = ?";
        try {
            queryRunner.update(sql,id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据留言id删除评论
     * @param id 留言id
     */
    public void delByLyId(int id,int aid) {
        String sql ="delete from comment where liuyanId = ? and articleId = ?";
        try {
            queryRunner.update(sql,id,aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
